package com.wash.shoes.common.typehandler;

import cn.hutool.core.collection.CollectionUtil;
import com.wash.shoes.common.enums.FactoryServiceTypeEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 工厂服务类型枚举转换
 */
public class FactoryServiceTypeHandler extends BaseTypeHandler<List<FactoryServiceTypeEnum>> {

    private static final String SEPARATOR = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<FactoryServiceTypeEnum> parameter, JdbcType jdbcType) throws SQLException {
        if (CollectionUtil.isNotEmpty(parameter)) {
            //转换成code,并拼成字符串
            Set<String> serviceTypeCodes = parameter.stream().map(FactoryServiceTypeEnum::getCode).collect(Collectors.toSet());
            String serviceTypeCodesStr = CollectionUtil.join(serviceTypeCodes, SEPARATOR);
            ps.setString(i, serviceTypeCodesStr);
        }
    }

    @Override
    public List<FactoryServiceTypeEnum> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String serviceTypeCodesStr = rs.getString(columnName);
        return getServiceType(serviceTypeCodesStr);
    }

    private List<FactoryServiceTypeEnum> getServiceType(String serviceTypeCodesStr) {
        if (serviceTypeCodesStr == null) {
            return null;
        }
        String[] serviceTypeCodes = serviceTypeCodesStr.split(SEPARATOR);
        return CollectionUtil.newArrayList(serviceTypeCodes).stream().map(FactoryServiceTypeEnum::getEnumByCode).collect(Collectors.toList());
    }


    @Override
    public List<FactoryServiceTypeEnum> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String serviceTypeCodesStr = rs.getString(columnIndex);
        return getServiceType(serviceTypeCodesStr);
    }

    @Override
    public List<FactoryServiceTypeEnum> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String serviceTypeCodesStr = cs.getString(columnIndex);
        return getServiceType(serviceTypeCodesStr);
    }
}
